<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="vue项目axios封装与mock等使用"><meta name="keywords" content="vue 项目"><meta name="author" content="晟松"><meta name="copyright" content="晟松"><title>vue项目axios封装与mock等使用 | 晟松</title><link rel="shortcut icon" href="/logo.png"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?c34d81d53341febe06a155941e2df16d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-axios%E5%B0%81%E8%A3%85%E5%92%8C%E8%AF%B7%E6%B1%82%E5%93%8D%E5%BA%94%E5%8A%AB%E6%8C%81"><span class="toc-number">1.</span> <span class="toc-text">1.axios封装和请求响应劫持</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-mock-js%E6%A8%A1%E6%8B%9F%E5%90%8E%E7%AB%AF%E6%95%B0%E6%8D%AE"><span class="toc-number">2.</span> <span class="toc-text">2.mock.js模拟后端数据</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-%E5%B8%83%E5%B1%80"><span class="toc-number">3.</span> <span class="toc-text">3.布局</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#4-%E5%9B%BE%E6%A0%87%E4%BD%BF%E7%94%A8"><span class="toc-number">4.</span> <span class="toc-text">4.图标使用</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#5-%E7%BB%84%E4%BB%B6"><span class="toc-number">5.</span> <span class="toc-text">5.组件</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">晟松</div><div class="author-info__description text-center">晟松的博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://gitee.com/cheng_song">Gitee</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">52</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">45</span></a></div></div></div><div id="content-outer"><div id="top-container" style="background-image: url(/img/blog-bg.jpg)"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">晟松</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">vue项目axios封装与mock等使用</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2020-08-22</time><div class="post-meta-wordcount"><span>字数总计: </span><span class="word-count">906</span><span class="post-meta__separator">|</span><span>阅读时长: 3 分钟</span></div></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>大概就是对B站老陈的一个vue企业项目视频的细节抄写</p>
<h5 id="1-axios封装和请求响应劫持"><a href="#1-axios封装和请求响应劫持" class="headerlink" title="1.axios封装和请求响应劫持"></a>1.axios封装和请求响应劫持</h5><p>对将后端传回的数据，前端需要自己对数据进行一个拦截检查，看数据是否正确。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="title">interceptors</span>(<span class="params">instance,url</span>)</span>&#123;</span><br><span class="line">        instance.interceptors.request.use(<span class="function">(<span class="params">config</span>)=&gt;</span>&#123;</span><br><span class="line">            <span class="comment">//处理config</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;拦截和处理请求&#x27;</span>)</span><br><span class="line">            config.data = &#123;</span><br><span class="line">                <span class="attr">msg</span>:<span class="string">&quot;helloworld&quot;</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="built_in">console</span>.log(config)</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">return</span> config</span><br><span class="line">        &#125;)</span><br><span class="line">        instance.interceptors.response.use(<span class="function">(<span class="params">res</span>)=&gt;</span>&#123;</span><br><span class="line">            <span class="comment">//处理响应</span></span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&quot;处理响应&quot;</span>)</span><br><span class="line">            <span class="comment">//console.log(res)</span></span><br><span class="line">            <span class="keyword">return</span> res.data</span><br><span class="line">        &#125;,<span class="function">(<span class="params">error</span>)=&gt;</span>&#123;</span><br><span class="line">            <span class="comment">//请求出问题，处理问题</span></span><br><span class="line">            <span class="built_in">console</span>.log(error)</span><br><span class="line">            <span class="keyword">return</span> &#123;<span class="attr">error</span>:<span class="string">&quot;网络出错了&quot;</span>&#125;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>跨域的处理，一般是在后端设置一个中间件，允许进行跨域请求</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"> app.use(<span class="function">(<span class="params">req,res,next</span>)=&gt;</span>&#123;</span><br><span class="line">    res.append(<span class="string">&#x27;Access-Control-Allow-Origin&#x27;</span>,<span class="string">&quot;*&quot;</span>);</span><br><span class="line">    res.append(<span class="string">&#x27;Access-Control-Allow-headers&#x27;</span>,<span class="string">&quot;*&quot;</span>)</span><br><span class="line">    next()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>或者设置一个代理服务，使用8080的本地端口作为代理去进行后端数据请求，之后再通过8080端口将数据返回。</p>
<p>设置代理服务器，使用vue-cli的自带配置vue.config.js。在vue-cli官网配置指南里面有专门的文档</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">devServer:&#123;<span class="comment">//设置代理服务器跨域请求</span></span><br><span class="line">        <span class="attr">proxy</span>:&#123;</span><br><span class="line">            <span class="string">&#x27;/api&#x27;</span>:&#123;</span><br><span class="line">                <span class="attr">target</span>:<span class="string">&quot;http://localhost:3000&quot;</span>,</span><br><span class="line">                <span class="attr">pathRewrite</span>:&#123;<span class="comment">//重写访问路径，这里是变为空</span></span><br><span class="line">                    <span class="string">&#x27;^/api&#x27;</span>:<span class="string">&quot;&quot;</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h5 id="2-mock-js模拟后端数据"><a href="#2-mock-js模拟后端数据" class="headerlink" title="2.mock.js模拟后端数据"></a>2.mock.js模拟后端数据</h5><p>通过劫持axios请求，将数据返回。路径可使用正则表达式</p>
<p>首先需要在main.js里面进行引入，如果是在开发模式。需要npm安装。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> Mock <span class="keyword">from</span> <span class="string">&#x27;mockjs&#x27;</span>;</span><br><span class="line">Mock.mock(<span class="string">&#x27;/api/posi&#x27;</span>,position)<span class="comment">//position和index_entry是数据。需要自己定义数据export dedfault导出</span></span><br><span class="line">Mock.mock(<span class="string">&#x27;/api/index_entry&#x27;</span>,index_entry)</span><br><span class="line"></span><br><span class="line"><span class="comment">//或者</span></span><br><span class="line">Mock.mock(<span class="string">&#x27;/api/user&#x27;</span>,&#123;</span><br><span class="line">    <span class="attr">username</span>:<span class="string">&quot;老陈&quot;</span>,</span><br><span class="line">    <span class="attr">age</span>:<span class="number">18</span>,</span><br><span class="line">    <span class="attr">gender</span>:<span class="string">&quot;男&quot;</span>,</span><br><span class="line">    <span class="attr">type</span>:<span class="string">&quot;帅&quot;</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>特别的重点是mock可进行随机数据生成，不用自己去想这些随机数据</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="string">&#x27;name|min-max&#x27;</span>: string</span><br><span class="line">Mock.mock(&#123;</span><br><span class="line">  <span class="string">&quot;string|1-10&quot;</span>: <span class="string">&quot;★&quot;</span><span class="comment">//结果为1-10颗★</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="string">&#x27;name|min-max&#x27;</span>: number</span><br><span class="line">Mock.mock(&#123;</span><br><span class="line">  <span class="string">&quot;number|1-100&quot;</span>: <span class="number">100</span><span class="comment">//结果为1-100里的一个数字</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p><a target="_blank" rel="noopener" href="http://mockjs.com/examples.html#Image">具体详细操作查看官方文档</a></p>
<h5 id="3-布局"><a href="#3-布局" class="headerlink" title="3.布局"></a>3.布局</h5><p>对于一个项目来说，需要响应式的进行布局，可以在任何常用设备上的布局比例不变，一般使用响应式进行操作布局。此项目使用rem布局，大概就是可根据屏幕的大小进行字体的大小调整。</p>
<p>相当于先确定一个px大小，例如100px为一个标准1rem。后面都通过这个标准1rem进行调整大小。</p>
<h5 id="4-图标使用"><a href="#4-图标使用" class="headerlink" title="4.图标使用"></a>4.图标使用</h5><p>一般可在iconfont里面找到想要的图标并添加进购物车，选择fontclass方式进行下载到本地，之后里面会有一个html文件教你怎么进行使用，一般是将图标文件放入到项目里的public文件夹里面的一个样式文件夹。之后在public里面的index.html里面进行css文件引入。</p>
<p><img src="C:\Users\admin\AppData\Roaming\Typora\typora-user-images\image-20200823102646390.png" alt="image-20200823102646390"></p>
<h5 id="5-组件"><a href="#5-组件" class="headerlink" title="5.组件"></a>5.组件</h5><p>全部导入一般是用在开发环境之下，真正的使用都是按需使用，具体查看官方文档</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">//全部导入</span></span><br><span class="line"><span class="comment">//main.js</span></span><br><span class="line"><span class="keyword">import</span> Vant <span class="keyword">from</span> <span class="string">&#x27;vant&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="string">&#x27;vant/lib/index.css&#x27;</span>;</span><br><span class="line">Vue.use(Vant);</span><br><span class="line"><span class="comment">//xxx.vue</span></span><br><span class="line"><span class="keyword">import</span> Button <span class="keyword">from</span> <span class="string">&#x27;vant/lib/button&#x27;</span>;</span><br><span class="line">components: &#123;Button&#125;<span class="comment">//需要注册</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">//按需导入，需要npm安装一个babel-plugin-import插件，并在babel.config.js里面进行一些修改，具体查看官方文档</span></span><br><span class="line"><span class="comment">//xxx.vue</span></span><br><span class="line"><span class="keyword">import</span> &#123; NavBar,Icon ,Swipe, SwipeItem,Grid, GridItem,Image &#125; <span class="keyword">from</span> <span class="string">&#x27;vant&#x27;</span>;</span><br><span class="line">components: &#123;NavBar,Icon ,Swipe, SwipeItem,Grid, GridItem,Image &#125;<span class="comment">//依旧需要注册</span></span><br></pre></td></tr></table></figure>

</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">晟松</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://chengsong.info/2020/08/22/vue项目axios封装与mock使用/">https://chengsong.info/2020/08/22/vue项目axios封装与mock使用/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://chengsong.info">晟松</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/vue-%E9%A1%B9%E7%9B%AE/">vue 项目</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2020/08/24/%E6%AD%A3%E5%88%99%E5%85%A5%E9%97%A8%E7%AC%94%E8%AE%B0/"><i class="fa fa-chevron-left">  </i><span>正则入门笔记</span></a></div><div class="next-post pull-right"><a href="/2020/08/04/node-js%E5%88%9D%E5%AD%A6%E4%B9%A0/"><span>node.js初学习</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer class="footer-bg" style="background-image: url(/img/blog-bg.jpg)"><div class="layout" id="footer"><div class="copyright">&copy;2020 - 2023 By 晟松</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="icp"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><span>湘ICP备2020021729号</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>